<?php


require_once "../core.php";


/**
 * wechat php test
 */

//define your token
define("TOKEN", "ekNTuqoa9pwvukw2BJ7M");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if ($this->checkSignature()) {
            $this->responseMsg();
            exit;
        }
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)) {
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            file_put_contents("temp\\dl111111dl.php","<?php return ".var_export($postObj, true)."; ?>",FILE_APPEND|LOCK_EX);
            if($postObj->MsgType=="event"){
                switch($postObj->Event){
                    case "user_scan_product_enter_session":
                        //$this->put_file(strval($postObj->ExtInfo), $postObj->FromUserName);
                        break;
                    case "subscribe":
                        AddNewUser(strval($postObj->EventKey), $postObj->FromUserName);
                        break;
                    case "SCAN":
                        put_file(strval($postObj->EventKey), $postObj->FromUserName);
                        break;
                    case "VIEW":
                        if($postObj->EventKey=="http://lch.chinacloudsites.cn/index.php"){
                            intoIndex($postObj->FromUserName);
                        }
                        break;
                }
            }

            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
            if (!empty($keyword)||$postObj->Event=="subscribe"||$postObj->Event=="SCAN") {
                $msgType = "text";
                $contentStr = "乐巢会欢迎您！";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            } else {
                echo "Input something...";
            }

        } else {
            echo "";
            exit;
        }
    }
}



function put_file($entInfo,$userName){
    if(!empty($entInfo)&&$entInfo<1000000&&$entInfo>99999){
        $arr=require "temp\\dl000000dl.php";
        if($arr==1){
            $arr=array();
        }
        $arr[$entInfo]=strval($userName);
        file_put_contents("temp\\dl000000dl.php","<?php return ".var_export($arr, true)."; ?>",LOCK_EX);
    }
}

function AddNewUser($entInfo,$userName){
    $entInfo=substr($entInfo,8 );
    $entInfo=((empty($entInfo)||$entInfo>100000)?null:$entInfo);
    global $core;
    $userInfo=GetUserInfo($userName);
    $core->AddUser($userName,null,$entInfo,$userInfo->headimgurl,$userInfo->nickname);
}

function intoIndex($userName){
    global $core;
    $userInfo=GetUserInfo($userName);
    /*file_put_contents("temp\\dl111111dl.php","<?php return ".var_export($userInfo, true)."; ?>",FILE_APPEND|LOCK_EX);*/
    if(!empty($user=$core->GetUserByWxId($userName))){
        /*file_put_contents("temp\\dl111111dl.php","<?php return ".var_export($user, true)."; ?>",FILE_APPEND|LOCK_EX);*/
        if(empty($user["name"])){
            $user["name"]=$userInfo->nickname;
        }
        if(empty($user["icon"])){
            $user["icon"]=$userInfo->headimgurl;
        }
        $core->UpdateUser($user["id"], $user["phone"],$user["icon"] , $user["name"]);
    }
}

?>